import { loc, loc_dt, obj_int, obj_str, uDb, cline } from 'sui';
import { User } from 'cache';
import { get_tp } from 'stock/base/cmd';

const add_order = (mod, val, cur, umd, submod) => {
    umd.startWait();

    const num = obj_int(val, "num");
    const dnum = obj_int(cur, "num");

    if (num > dnum) {
        umd.setErr(loc("l_753"));
        return;
    }

    uDb(null, "code/gen",
        {
            line: cline(),
            rule: "order",
        },
        code => {
            const cmd = {
                "line": cline(),
                "v": {
                    "sn": obj_str(code, "psn"),
                    "usn": User.userName(),
                    "uname": User.uName(),
                    "bsn": obj_str(cur, "sn"),
                    "tech": obj_str(cur, "tech"),
                    "ball": obj_str(cur, "ball"),
                    "state": "open",
                    "num": num,
                    "pstart": loc_dt(new Date()),
                    "mt": get_tp(mod),
                }
            };

            uDb(null, "order/add", cmd,
                r => {
                    umd.update(`file/md/${submod}`,
                        {
                            v: { st: "ok" },
                            sn: obj_str(cur, "sn"),
                        }, () => alert(loc("l_772")));
                }, e => umd.setErr());
        }, e => umd.setErr(loc("l_755")));
};

const fix_st = (v) => {
    const cmd = {
        "ok": loc("l_725"),
        "ng": loc("l_792"),
    };

    const f = cmd[v];
    if (f) {
        return f;
    }

    return v;
};

export {fix_st, add_order};
